import java.util.*;

public class PaperList {
    private final String teacher;
    private final List<Paper> papers;
    private final PaperSelection selections = new PaperSelection();
    private PaperSelectionStrategy strategy = new RandomSelectionStrategy();
    // PaperList.java
    private List<Paper> randomSelectPapers(List<Paper> availablePapers, int q) {
        Collections.shuffle(availablePapers);
        return new ArrayList<>(availablePapers.subList(0, q));
    }

    public PaperList(String teacher, List<Paper> papers) {
        this.teacher = teacher;
        this.papers = new ArrayList<>(papers);
    }

    public void setStrategy(PaperSelectionStrategy strategy) {
        this.strategy = strategy;
    }

    private List<Paper> getUnselectedPapersByType(PaperType type) {
        List<Paper> results = new ArrayList<>();
        for (Paper p : this.papers) {
            if (!this.selections.isSelected(p)) {
                if (type == PaperType.Any ||
                        p.getClass().getSimpleName().equals(type.name())) {
                    results.add(p);
                }
            }
        }
        return Collections.unmodifiableList(results);
    }

    public synchronized List<Paper> selectPaper(Student student)
            throws NoEnoughPapersException, IllegalArgumentException {

        if (student == null) {
            throw new IllegalArgumentException("学生对象不能为null");
        }
        if (student.getPreferredPaperType() == null) {
            throw new IllegalArgumentException("论文类型不能为null");
        }
        if (student.getPreferredQuantity() < 1 || student.getPreferredQuantity() > 4) {
            throw new IllegalArgumentException("论文数量必须在1-4之间");
        }

        Set<Student> studentsWithSelections = selections.getStudentsWithSelections();
        if (studentsWithSelections.contains(student)) {
            throw new IllegalArgumentException(
                    "学生" + student.getName() + "已选择论文");
        }

        List<Paper> available = getUnselectedPapersByType(student.getPreferredPaperType());

        if (available.size() < student.getPreferredQuantity()) {
            throw new NoEnoughPapersException(
                    "学生 " + student.getName() +
                            " 希望选论文 " + student.getPreferredQuantity() +
                            " 篇，但目前只有 " + available.size() + " 篇可选"
            );
        }

        List<Paper> selected = strategy.selectPapers(available, student.getPreferredQuantity());

        for (Paper p : selected) {
            selections.addSelection(student, p);
        }

        return selected;
    }

    public PaperSelection getSelectionResult() {
        return this.selections;
    }
}